<!--suppress ALL -->
<template>
  <div class="app-container" id="app-main">
    <!-- 查询和其他操作 -->
    <div>
      <div class="filter-container">
        <el-input
          v-model="query.name"
          clearable
          style="width: 200px"
          class="filter-item-left"
          size="small"
          :placeholder="$t('message.validate.input')"
        />
        <el-button class="filter-item-right" size="small" icon="el-icon-search" @click="handleFind">
          {{ $t('message.operate.search') }}
        </el-button>
      </div>
      <div class="filter-container2">
        <el-button
          v-limit="'XTGL:CDGL:ADD'"
          class="filter-item"
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
        >
          {{ $t('message.operate.addMenu') }}
        </el-button>
      </div>
    </div>

    <el-table
      ref="tableDom"
      v-loading="loading"
      :data="tableTreeData"
      style="width: 100%"
      row-key="menuId"
      lazy
      :max-height="maxHeight"
      :load="load"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" :label="$t('message.menu.name')" sortable width="180" />
      <el-table-column prop="enName" :label="$t('message.menu.enName')" sortable width="180" />
      <!-- <el-table-column :label="$t('message.menu.icon')" align="center">
        <template #default="scope">
          <svg-icon :icon-class="scope.row.icon" />
        </template>
      </el-table-column> -->

      <el-table-column :label="$t('message.menu.type')" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.type === 0" size="small">{{ $t('message.menu.fold') }}</el-tag>
          <el-tag v-else-if="scope.row.type === 1" size="small" type="success">
            {{ $t('message.menu.name') }}
          </el-tag>
          <el-tag v-else-if="scope.row.type === 2" size="small" type="info">
            {{ $t('message.menu.button') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="parentName" :label="$t('message.menu.super')" align="center" />
      <el-table-column prop="path" :label="$t('message.menu.path')" align="center" />
      <el-table-column
        prop="component"
        :label="$t('message.menu.component')"
        align="center"
        width="120"
      />
      <!-- <el-table-column prop="perms" :label="$t('message.menu.perms')" align="center" width="180" /> -->
      <el-table-column prop="sort" :label="$t('message.table.sort')" align="center" />
      <el-table-column
        :label="$t('message.operate.name')"
        fixed="right"
        min-width="150"
        align="center"
      >
        <template #default="scope">
          <el-button
            v-limit="'XTGL:CDGL:EDIT'"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >
            {{ $t('message.operate.edit') }}
          </el-button>
          <el-button
            v-limit="'XTGL:CDGL:DELETE'"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >
            {{ $t('message.operate.delete') }}
          </el-button>
          <el-button
            v-limit="'XTGL:CDGL:ADDSUB'"
            v-if="scope.row.type != 2"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
          >
            {{ $t('message.operate.addChildren') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新增修改界面 -->
    <el-dialog
      v-model="dialogVisible"
      :title="!dataForm.menuId ? $t('message.operate.add') : $t('message.operate.edit')"
      :close-on-click-modal="false"
      :width="dialogWidth"
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="dataRule"
        label-width="130px"
        :size="size"
        style="text-align: left"
      >
        <el-form-item :label="$t('message.menu.type')" prop="type">
          <el-radio-group v-model="dataForm.type" class="radio">
            <el-radio v-for="(type, index) in menuTypeList" :key="index" :label="index">
              {{ type }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="menuTypeList[dataForm.type] + $t('message.form.name')" prop="name">
          <el-input
            v-model="dataForm.name"
            :placeholder="menuTypeList[dataForm.type] + $t('message.form.name')"
          />
        </el-form-item>
        <el-form-item
          :label="menuTypeList[dataForm.type] + $t('message.form.enName')"
          prop="enName"
        >
          <el-input
            v-model="dataForm.enName"
            :placeholder="menuTypeList[dataForm.type] + $t('message.form.enName')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.menu.super')" prop="parentName">
          <popup-tree-input
            :data="popupTreeData"
            :disabled="ifAddTop"
            :props="popupTreeProps"
            :prop="
              dataForm.parentName == null || dataForm.parentName === ''
                ? $t('message.menu.root')
                : dataForm.parentName
            "
            :node-key="'' + dataForm.parentId"
            :current-change-handle="handleTreeSelectChange"
          />
        </el-form-item>
        <el-form-item
          v-if="dataForm.type !== 0"
          :label="$t('message.menu.authorization')"
          prop="perms"
        >
          <el-input
            v-model="dataForm.perms"
            placeholder="如: sys:user:add, sys:user:edit, sys:user:delete"
          />
        </el-form-item>
        <el-form-item
          v-if="dataForm.type === 2"
          :label="$t('message.menu.processIden')"
          prop="processId"
        >
          <el-select
            v-model="dataForm.processId"
            :placeholder="$t('message.menu.placeholder') + $t('message.menu.processIden')"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in processIds"
              :key="item.id"
              :label="item.processName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dataForm.type !== 2" :label="$t('message.menu.inner')" prop="isFrame">
          <div class="radio">
            <el-radio v-model="dataForm.isFrame" label="true">{{
              $t('message.menu.true')
            }}</el-radio>
            <el-radio v-model="dataForm.isFrame" label="false">
              {{ $t('message.menu.false') }}
            </el-radio>
          </div>
        </el-form-item>

        <el-form-item v-if="dataForm.type !== 2" :label="$t('message.menu.icon')">
          <el-upload
            v-model:file-list="iconFile"
            ref="uploadRef"
            :limit="1"
            :headers="headers"
            accept="image/*"
            action="/fastDfs/file/upload"
            :on-success="handleIcon"
            :on-preview="previewIcon"
          >
            <el-button type="primary">点击上传图标</el-button>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item v-if="dataForm.type !== 2" :label="$t('message.menu.icon')">
          <el-popover
            placement="bottom-start"
            width="460"
            trigger="click"
            @show="$refs['iconSelect'].reset()"
          >
            <icon-select ref="iconSelect" @selected="selected" />
            <template #reference>
              <el-input
                v-model="dataForm.icon"
                :placeholder="$t('message.validate.select')"
                clearable
              >
                <template v-if="dataForm.icon" #prefix>
                  <svg-icon
                    :icon-class="dataForm.icon"
                    class="el-input__icon"
                    style="height: 32px; width: 16px"
                  />
                </template>
                <template v-else #prefix>
                  <i class="el-input__icon el-icon-search" />
                </template>
              </el-input>
            </template>
          </el-popover>
        </el-form-item> -->

        <!--  <el-form-item :label="$t('message.menu.iconSize')">
          <el-input-number
            v-model="dataForm.iconSize"
            controls-position="right"
            min="0"
            style="width: 100%"
            :placeholder="$t('message.menu.defaultSize')"
          />
        </el-form-item>
        <el-form-item :label="$t('message.menu.iconColor')">
          <el-input v-model="dataForm.iconColor" />
        </el-form-item> -->
        <!-- <el-form-item v-if="dataForm.type !== 2" :label="$t('message.menu.ip')">
          <el-row>
            <el-col :span="22">
              <el-input v-model="dataForm.ip" @blur="ifHttp(dataForm.ip)" />
            </el-col>
            <el-col :span="2" class="icon-list__tips">
              <el-tooltip placement="top" effect="light" style="padding: 10px" content="">
                <template #content>
                  <p>{{ $t('message.menu.tooltip.ip') }}</p>
                </template>
                <i class="el-icon-warning" />
              </el-tooltip>
            </el-col>
          </el-row>
        </el-form-item> -->

        <!-- v-if="dataForm.isFrame === 'true'" -->
        <el-form-item
          :label="$t('message.menu.routerComponent')"
          prop="component"
        >
          <el-row>
            <el-col :span="22">
              <el-input
                v-model="dataForm.component"
                :placeholder="$t('message.menu.routerComponent')"
              />
            </el-col>
            <el-col :span="2" class="icon-list__tips">
              <el-tooltip placement="top" effect="light" style="padding: 10px" content="">
                <template #content>
                  <p>{{ $t('message.menu.urlFormate') }}</p>
                  <p>{{ $t('message.menu.tooltip.url') }}</p>
                </template>
                <i class="el-icon-warning" />
              </el-tooltip>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item v-if="dataForm.type !== 2" :label="$t('message.menu.path')" prop="path">
          <el-input v-model="dataForm.path" :placeholder="$t('message.menu.path')" />
        </el-form-item>
        <el-form-item v-if="dataForm.type === 2" :label="$t('message.menu.url')" prop="url">
          <el-input v-model="dataForm.url" :placeholder="$t('message.menu.url')" />
        </el-form-item>
        <el-form-item
          v-if="dataForm.type === 2"
          :label="$t('message.menu.serviceUrl')"
          prop="serviceUrl"
        >
          <el-input v-model="dataForm.serviceUrl" :placeholder="$t('message.menu.serviceUrl')" />
        </el-form-item>
        <!-- <el-form-item
          v-if="dataForm.type !== 2"
          :label="$t('message.menu.placeLocation')"
          prop="placeLocation"
        >
          <el-select
            v-model="dataForm.placeLocation"
            :disabled="ifLocDisable"
            :placeholder="$t('message.menu.placeLocationHolder')"
          >
            <el-option
              v-for="item in placeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item
          v-show="
            (dataForm.type !== 2 && whetherSsoFlag == true) ||
              (dataForm.type !== 2 && dataForm.whetherSso != '')
          "
          :label="$t('message.menu.whetherSso')"
          prop="whetherSso"
        >
          <el-select v-model="dataForm.whetherSso" :placeholder="$t('message.menu.whetherSso')">
            <el-option label="是" value="1"></el-option>
            <el-option label="不是" value="0"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item v-if="dataForm.type !== 2" :label="$t('message.menu.index')" prop="sort">
          <el-input-number
            v-model="dataForm.sort"
            controls-position="right"
            :min="0"
            :label="$t('message.menu.index')"
          />
        </el-form-item>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button @click="dialogVisible = false">{{ $t('message.operate.cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t('message.operate.confirm') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import PopupTreeInput from './components/MenuTree'
import IconSelect from '@/components/IconSelect'
// import { mapGetters } from 'vuex'
import { ElMessage } from 'element-plus'
import {
  saveMenu,
  getMenuTree,
  updateMenu,
  deleteMenu,
  getChildrenMenu,
  processIden,
} from '../api/menu'

export default {
  components: { PopupTreeInput, IconSelect },
  data() {
    return {
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('token'),
      },
      size: 'small',
      query: {
        name: undefined,
      },
      formLabelWidth: '120px',
      isEditForm: false,
      loading: false,
      dialogVisible: false, // 控制弹出框
      menuTypeList: ['目录', '菜单', '按钮'],
      dataForm: {
        menuId: 0,
        type: 1,
        name: '',
        enName: '',
        parentId: 0,
        component: '',
        isFrame: 'false',
        frameFlag: 0,
        parentName: '主页',
        path: '',
        perms: '',
        sort: 0,
        icon: '',
        ip: '', //微应用ip地址
        iconSize: '', //图标大小
        iconColor: '', // 图标颜色
        serviceUrl: '', //服务名
        placeLocation: '', //菜单位置,
        whetherSso: '', //是否集成统一认证
        url: '',
        processId: '',
      },
      tableTreeData: [],
      maps: new Map(),
      operateRow: {},
      ifAddTop: false,
      whetherSsoFlag: false,
      // 表单校验
      dataRule: {
        name: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
        enName: [{ required: true, message: '英文菜单名称不能为空', trigger: 'blur' }],
      },
      // 菜单位置
      ifLocDisable: false,

      placeOptions: [
        {
          value: 'top',
          label: '上部',
        },
        {
          value: 'left',
          label: '左侧',
        },
        {
          value: 'other',
          label: '其他',
        },
      ],
      popupTreeData: [],
      popupTreeProps: {
        label: 'name',
        children: 'children',
        isLeaf: ({ hasChildren }) => !hasChildren,
      },
      key: 1,
      columns: [
        {
          label: '名称',
          key: 'name',
          expand: true,
          width: 220,
          align: 'center',
        },
        {
          label: '图标',
          key: 'icon',
          width: 50,
        },
        {
          label: '类型',
          key: 'type',
          width: 80,
        },
        {
          label: '上级菜单',
          key: 'parentName',
          align: 'center',
          width: 100,
        },
        {
          label: '菜单URL',
          key: 'path',
          align: 'center',
        },
        {
          label: '菜单组件',
          key: 'component',
          align: 'center',
          width: 100,
        },
        {
          label: '授权标识',
          key: 'perms',
          align: 'center',
        },
        {
          label: '排序',
          key: 'sort',
          align: 'center',
          width: 50,
        },
        {
          label: '操作',
          key: 'operation',
          fixed: 'right',
          width: 180,
        },
      ],
      processIds: [],
      height: 0,
    }
  },
  computed: {
    maxHeight() {
      return this.height - 138
    },
    // ...mapGetters(['maxHeightTable', 'ismobile']),
    iconFile (){
      // return getFileList('softwareScreenshot')
      if (this.dataForm.icon) {
        let fileList = [JSON.parse(this.dataForm.icon)]
        // console.log(fileList, 'fileList')
        return fileList
      } else {
        return []
      }
    }
  },
  created() {
    this.findTreeData()
    this.setDialogWidth()
    this.getprocessId()
  },
  mounted() {
    this.height = document.getElementById('app-main').offsetHeight
  },
  methods: {
    handleIcon (uploadFile) {
      if (uploadFile.code == 200) {
        ElMessage({
          message: '上传成功',
          type: 'success',
        })
        console.log('上传成功uploadFile', uploadFile)
        let obj = {
          name: uploadFile.data.fileName,
          url: uploadFile.data.path,
        }
        let url = JSON.stringify(obj)
        this.dataForm.icon = url
        console.log(this.dataForm.icon, 'this.dataForm.icon')
      } else {
        ElMessage({
          message: '上传失败',
          type: 'error',
        })
      }
    },
    previewIcon(){
      console.log(this.dataForm.icon, 'this.dataForm.icon')
      // window.open(
      //   'http://www.pfile.com.cn/api/profile/onlinePreview?url=' +
      //     encodeURIComponent(JSON.parse(this.dataForm.icon).url)
      // )
      window.open(JSON.parse(this.dataForm.icon).url)
    },
    setDialogWidth() {
      this.dialogWidth = '50%'
      // if (this.ismobile) {
      //   this.dialogWidth = '90%'
      // } else {
      //   this.dialogWidth = '50%'
      // }
    },
    selected(name) {
      this.dataForm.icon = name
    },
    ifHttp(str) {
      // eslint-disable-next-line no-useless-escape
      const num = str.search('^(http|https):\/\/')
      if (num != -1) this.whetherSsoFlag = true
      else this.whetherSsoFlag = false
    },
    load(tree, treeNode, resolve) {
      const pid = tree.menuId
      this.maps.set(pid, { tree, treeNode, resolve })
      getChildrenMenu(pid).then(({ data }) => {
        resolve(data.data)
      })
    },
    // 菜单增删改后调用
    reload(pid) {
      if (this.maps.has(pid)) {
        const { tree, treeNode, resolve } = this.maps.get(pid) //根据pid取出对应的节点数据
        this.load(tree, treeNode, resolve)
        if (tree.parentId != '0') {
          this.reload(tree.parentId)
        }
      }
    },
    // 获取数据
    findTreeData: function () {
      this.loading = true
      getMenuTree(this.query).then((res) => {
        this.tableTreeData = res.data.data
        this.loading = false
        this.popupTreeData = this.getParentMenuTree(res.data.data)
      })
    },
    getprocessId() {
      processIden().then((res) => {
        this.processIds = res.data.data
      })
    },
    // 获取上级菜单树
    getParentMenuTree: function (tableTreeDdata) {
      const parent = {
        parentId: 0,
        name: '根节点',
        children: tableTreeDdata,
        hasChildren: true,
      }
      return [parent]
    },

    handleFind: function () {
      this.findTreeData()
    },
    initOptions() {
      if (this.placeOptions.length < 3) {
        this.placeOptions.unshift({
          value: 'top',
          label: '上部',
        })
      }
    },
    // 显示新增界面
    handleAdd: function (row) {
      this.operateRow = row
      this.dialogVisible = true
      this.isEditForm = false
      this.ifLocDisable = false
      this.initOptions()
      this.dataForm = {
        menuId: 0,
        type: 1,
        name: '',
        parentId: 0,
        component: '',
        isFrame: 'true',
        ip: '',
        parentName: '',
        path: '',
        perms: '',
        sort: 0,
        icon: '',
        url: '',
        serviceUrl: '',
        placeLocation: '',
        whetherSso: '',
        processId: '',
      }
      if (row.name) {
        this.ifAddTop = false
        this.dataForm.parentId = row.menuId
        this.dataForm.parentName = row.name
        if (row.parentId != '0' && row.placeLocation != 'top') {
          this.placeOptions.shift()
          this.dataForm.placeLocation = 'left'
        }
      } else {
        this.ifAddTop = true
        this.ifLocDisable = true
        this.dataForm.placeLocation = 'top'
      }
    },
    // 显示编辑页面
    handleEdit: function (row) {
      this.isEditForm = true
      this.dialogVisible = true
      this.ifLocDisable = false
      this.initOptions()
      const {
        menuId,
        type,
        name,
        enName,
        parentId,
        parentName,
        isFrame,
        component,
        path,
        perms,
        sort,
        icon,
        url,
        serviceUrl,
        placeLocation,
        whetherSso,
        ip,
        hasChildren,
        processId,
      } = row
      this.dataForm.menuId = menuId
      this.dataForm.type = type
      this.dataForm.name = name
      this.dataForm.enName = enName
      this.dataForm.parentId = parentId
      this.dataForm.component = component
      this.dataForm.parentName = parentName
      this.dataForm.isFrame = '' + isFrame
      this.dataForm.path = path
      this.dataForm.ip = ip
      this.dataForm.perms = perms
      this.dataForm.sort = sort
      this.dataForm.icon = icon
      this.dataForm.url = url
      this.dataForm.processId = processId
      ;(this.dataForm.serviceUrl = serviceUrl),
        (this.dataForm.placeLocation = placeLocation),
        (this.dataForm.whetherSso = whetherSso),
        (this.dataForm.hasChildren = hasChildren)
    },
    // 菜单树选中
    handleTreeSelectChange(data) {
      this.dataForm.parentId = data.menuId
      this.dataForm.parentName = data.name
    },
    // 删除操作
    handleDelete(row) {
      // const that = this
      this.$confirm(this.$i18n.t('message.menu.delete'), this.$i18n.t('message.menu.hint'), {
        confirmButtonText: this.$i18n.t('message.operate.confirm'),
        cancelButtonText: this.$i18n.t('message.operate.cancel'),
        type: 'warning',
      }).then(() => {
        deleteMenu(row.menuId).then((response) => {
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              message: response.data.msg,
            })
            this.findTreeData()
            this.reload(row.parentId)
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg,
            })
          }
        })
      })
    },

    // 新增修改操作
    submitForm: function () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.isEditForm) {
            const params = Object.assign({}, this.dataForm)
            saveMenu(params).then((response) => {
              if (response.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: response.data.msg,
                })
                this.dialogVisible = false
                this.findTreeData()
                this.operateRow.hasChildren = true
                this.reload(params.parentId)
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.msg,
                })
              }
            })
          } else {
            updateMenu(this.dataForm).then((response) => {
              if (response.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: response.data.msg,
                })
                this.dialogVisible = false
                this.findTreeData()
                this.reload(this.dataForm.parentId)
              } else {
                this.$message({
                  type: 'error',
                  message: response.data,
                })
              }
            })
          }
        }
      })
    },
  },
  watch: {
    'dataForm.isFrame'(newVal) {
      console.log(newVal, 'isFrame')
      if (newVal) {
        this.frameFlag = 1
      } else {
        this.frameFlag = 0
      }
    },
  },
}
</script>
<style scoped>
.filter-item {
  margin-left: 20px;
  caret-color: aliceblue;
}
.radio {
  display: flex;
  margin-top: 10px;
}
:deep(.el-upload-list__item.is-success.focusing .el-icon-close-tip) {
  display: none !important;
}
</style>
